/*
Copyright 2011 Raymond Giorgi

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at

   http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
 */

package edu.pitt.cs3530.scripts;

import java.io.IOException;
import java.io.ObjectOutputStream;
import java.net.ServerSocket;
import java.net.Socket;

import edu.pitt.cs3530.messages.ControlMessage;

/**
 * This class will accept connections from application servers trying to connect
 * and automatically put them to sleep.
 */
public class ShutDownMachinesScript {

	/**
	 * The main method will accept connections from application servers and shut
	 * them down. After the specified number of machines connect, the program
	 * will stop
	 * 
	 * @param args
	 *            The first argument is the port number; the second argument is
	 *            the number of machines that should be shut down
	 */
	public static void main(String args[]) {
		if (args.length != 2) {
			System.out
					.println("Usage: ShutDownMachinesScript [port] [numberOfMachines]");
			System.exit(0);
		}
		int port = Integer.parseInt(args[0]);
		int numberOfMachines = Integer.parseInt(args[1]);
		try {
			ServerSocket ss = new ServerSocket(port);
			for (int i = 0; i < numberOfMachines; i++) {
				Socket socket = ss.accept();
				ObjectOutputStream oos = new ObjectOutputStream(socket
						.getOutputStream());
				oos.writeObject(new ControlMessage(null, null,
						"/etc/acpi/sleep.sh"));
				oos.flush();
			}
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}

}
